﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NFixedPoint;

namespace ColliderSystem
{
    public class NSphereCollider : IShape
    {
        public SphereInfo info;

        public NSphereCollider(SphereInfo info)
        {
            this.info = info;
            this.info.position.y = 0;
        }

        public IShape Intersects(IShape other)
        {
            if (other is NBoxCollider box)
            {
                if (Intersects(box))
                {
                    return box;
                }
            }
            else if (other is NSphereCollider sphere)
            {
                if (Intersects(sphere))
                {
                    return sphere;
                }
            }
            return null;
        }

        bool Intersects(NBoxCollider box)
        {
            //优化算法。把矩形当成圆形，判断一下距离。
            FixedPoint num = (info.radius + box.info.radius);
            if ((info.position - box.info.position).unsafeSqrMagnitude > num * num)
            {
                return false;
            }
            FixedPoint3 point = GetClosePoint(box);
            //圆形中点与最近点的距离。
            return (info.position - point).unsafeSqrMagnitude < info.radius * info.radius;
        }

        public FixedPoint3 GetClosePoint(NBoxCollider box)
        {
            //圆形到矩形的距离
            FixedPoint3 dis = info.position - box.info.position;

            //拿到矩形里面，距离圆形最近的点
            FixedPoint3 result;
            result = box.info.position;
            result +=
                FMath.Clamp(
                    FixedPoint3.Dot(dis, box.info.axis[0]),
                    -box.info.size.x,
                    box.info.size.x
                ) * box.info.axis[0];
            result +=
                FMath.Clamp(
                    FixedPoint3.Dot(dis, box.info.axis[2]),
                    -box.info.size.z,
                    box.info.size.z
                ) * box.info.axis[2];
            return result;
        }

        bool Intersects(NSphereCollider sphere)
        {
            //2个圆心的距离
            //如果距离的长度的平方>2个半径和的平方。
            FixedPoint value = info.radius + sphere.info.radius;
            //碰到了
            return (info.position - sphere.info.position).unsafeSqrMagnitude <= value * value;
        }
    }
}
